package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author Xanny
 */
@Component
@Slf4j
@RefreshScope
public class AuthFilter implements GlobalFilter, Ordered {
//
    @Value("${excludePaths}")
    private List<String> excludePaths;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("过滤器开始执行");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //解析当前文件的访问路径 判断是否需要放行 如果为登录请求则放行
        String path = request.getURI().getPath();
        if(excludePaths.contains(path)){
            log.info("该请求为登录请求，放行");
            return chain.filter(exchange);
        }
        List<String> headers = request.getHeaders().get("token");
        String token = headers.get(0);

        //校验是否存在token
        if (ObjectUtils.isEmpty(token)) {
            log.info("权限不足");
            response.setStatusCode(HttpStatus.NON_AUTHORITATIVE_INFORMATION);
            return response.setComplete();
        }

        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int flag = AppJwtUtil.verifyToken(claimsBody);
        //校验token是否过期
        if(flag == 1 || flag == 2){
            log.info("该token已过期");
            response.setStatusCode(HttpStatus.NON_AUTHORITATIVE_INFORMATION);
            return response.setComplete();
        }


//
//        response.addCookie();


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
